package com.atguigu.service.impl;

import com.atguigu.entity.PlatformPropertyKey;
import com.atguigu.entity.PlatformPropertyValue;
import com.atguigu.mapper.PlatformPropertyKeyMapper;
import com.atguigu.service.PlatformPropertyKeyService;
import com.atguigu.service.PlatformPropertyValueService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class PlatformPropertyKeyServiceImpl extends ServiceImpl<PlatformPropertyKeyMapper, PlatformPropertyKey> implements PlatformPropertyKeyService {
    @Autowired
    private PlatformPropertyValueService propertyValueService;

    @Override
    public List<PlatformPropertyKey> getPlatformPropertyByCategoryId(Long category1Id, Long category2Id, Long category3Id) {
        //第一种写法效率不高
        //b.根据分类id查询平台属性名称
//        List<PlatformPropertyKey> propertyKeyList=baseMapper.getPlatformPropertyByCategoryId(category1Id,category2Id,category3Id);
        //c.根据平台属性名称id查询平台属性值
//        for (PlatformPropertyKey propertyKey : propertyKeyList) {
//            List<PlatformPropertyValue> propertyValueList=propertyValueService.getPlatformPropertyValueByKeyId(propertyKey.getId());
//            propertyKey.setPropertyValueList(propertyValueList);
//        }
        //第二种写法 直接关联查询

        return baseMapper.getPlatformPropertyByCategoryId(category1Id,category2Id,category3Id);
    }

    @Override
    public void savePlatformProperty(PlatformPropertyKey platformPropertyKey) {
        if(platformPropertyKey.getId()!=null){
            baseMapper.updateById(platformPropertyKey);
            //不管添加还是修改都可以执行这个方法
            QueryWrapper<PlatformPropertyValue> wrapper = new QueryWrapper<>();
            wrapper.eq("property_key_id",platformPropertyKey.getId());
            propertyValueService.remove(wrapper);
        }else{
            //1.保存平台属性key
            baseMapper.insert(platformPropertyKey);
        }
        List<PlatformPropertyValue> propertyValueList = platformPropertyKey.getPropertyValueList();
        //判断平台属性值是否为空
        if(!CollectionUtils.isEmpty(propertyValueList)){
            for (PlatformPropertyValue platformPropertyValue : propertyValueList) {
                //该平台属性值属于那个平台属性key
                platformPropertyValue.setPropertyKeyId(platformPropertyKey.getId());
                //propertyValueService.save(platformPropertyValue);
            }
            //改为批处理
            propertyValueService.saveBatch(propertyValueList);
        }
    }

    @Override
    public List<PlatformPropertyKey> getPlatformPropertyBySkuId(Long skuId) {
        return baseMapper.getPlatformPropertyBySkuId(skuId);
    }
}
